package a归并;


public class 合并K个升序链表 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            int length = lists.length;
            //创建一个虚拟节点
            ListNode head = null;
            //处理边界条件
            if (length == 0) {
                return head;
            }
            for (int i = 0; i < length; i++) {
                head = hebing(head, lists[i]);
            }
            return head;
        }

        //处理两个有序链表的合并
        public ListNode hebing(ListNode a, ListNode b) {
            //定义一个临时的
            ListNode head = new ListNode(0);
            ListNode tmp = head;

            while (a != null && b != null) {
                if (a.val <= b.val) {
                    tmp.next = a;
                    a = a.next;
                } else {
                    tmp.next = b;
                    b = b.next;
                }
                tmp = tmp.next;
            }
            tmp.next = (a != null) ? a : b;
            return head.next;
        }
    }
}
